#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
using std::cout;
using std::cerr;
using std::endl;
using std::ifstream;
using std::string;

void test0(){
    ifstream ifs("explicit.cc");
    long pos = ifs.tellg();
    cout << pos << endl;

    ifs.seekg(0);
    pos = ifs.tellg();
    cout << pos << endl;

    string word;
    ifs >> word;
    cout << word << endl << endl;

    char * pdata = new char[100]();
    ifs.read(pdata,80);

    cout << pdata << endl;

    delete [] pdata;
    pdata = nullptr;

    ifs.close();
}

void test1(){
    //需求：读取文件中全部内容
    ifstream ifs("explicit.cc");

    if(!ifs){
        cerr << "ifstream open file failed" << endl;
        return;
    }

    //先将文件游标置为结尾位置,为了获取文件的长度
    ifs.seekg(0,std::ios::end);
    long length = ifs.tellg();
    cout << "length:" << length << endl;

    char * pdata = new char[length + 1]();
    //再讲文件游标置为开始位置，为了从开头往后读取内容
    ifs.seekg(0,std::ios::beg);
    ifs.read(pdata,length);

    cout << pdata << endl;

    delete [] pdata;
    pdata = nullptr;

    ifs.close();
}

void test2(){
    //需求：读取文件中全部内容
    //一开始就让文件游标处于结尾位置
    ifstream ifs("explicit.cc",std::ios::ate);

    if(!ifs){
        cerr << "ifstream open file failed" << endl;
        return;
    }

    long length = ifs.tellg();
    cout << "length:" << length << endl;

    char * pdata = new char[length + 1]();
    //再讲文件游标置为开始位置，为了从开头往后读取内容
    ifs.seekg(0);
    ifs.read(pdata,length);

    cout << pdata << endl;

    delete [] pdata;
    pdata = nullptr;

    ifs.close();
}

int main(void){
    test2();
    return 0;
}
